package com.java.hohenheim.springplatform.web.service;

import com.java.hohenheim.springplatform.conf.WeChatAppletConfig;
import com.java.hohenheim.springplatform.data.model.account.wx.WXAppletSessionRespModel;
import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.exception.PlatformException;
import com.java.hohenheim.springplatform.http.WXAppletClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Hohenheim
 * @date 2019/4/7
 * @description 微信用户系统服务
 */
@Service
@Slf4j
public class WXService {
    @Autowired
    private WeChatAppletConfig mWeChatAppletConfig;
    @Autowired
    private WXAppletClient mWXClient;

    /**
     * 获取微信小程序Session
     * @param authCode 授权码
     * @return Session请求结果
     */
    public WXAppletSessionRespModel wechatAppletSession(String authCode) {
        WXAppletSessionRespModel sessionModel = null;

        try {
            sessionModel = mWXClient.getWeChatAppletSession(mWeChatAppletConfig.getAppId(),
                    mWeChatAppletConfig.getSecret(), authCode, "authorization_code");
        }
        catch (Exception e) {
            log.error("微信登录", "小程序登录错误：" + e.getMessage(), e);
            throw new PlatformException(ResultCodes.LOGIN_FAIL);
        }

        return sessionModel;
    }
}